"""
任务管理器
负责协调不同任务模块的执行，确定任务优先级和执行顺序
"""

import logging
from typing import Dict, Any, List, Optional
from .product_query import ProductQueryTask
from .order_processing import OrderProcessingTask
from .customer_service import CustomerServiceTask

logger = logging.getLogger(__name__)

class TaskManager:
    """任务管理器"""
    
    def __init__(self):
        self.logger = logging.getLogger(f"{__name__}.TaskManager")
        
        # 初始化任务处理器
        self.tasks = {
            "product_query": ProductQueryTask(),
            "order_processing": OrderProcessingTask(),
            "customer_service": CustomerServiceTask()
        }
        
        # 任务优先级（数字越小优先级越高）
        self.task_priority = {
            "order_processing": 1,  # 下单优先级最高
            "product_query": 2,      # 商品查询次之
            "customer_service": 3    # 呼叫客服优先级最低
        }
        
        # 任务执行统计
        self.execution_stats = {
            "product_query": {"count": 0, "success": 0, "failed": 0},
            "order_processing": {"count": 0, "success": 0, "failed": 0},
            "customer_service": {"count": 0, "success": 0, "failed": 0}
        }
    
    def process_message(self, message: str, conversation_history: list, customer_id: str, existing_order_info: Dict = None) -> Dict[str, Any]:
        """
        处理客户消息，确定任务类型并执行
        
        Args:
            message: 客户消息
            conversation_history: 对话历史
            customer_id: 客户ID
            existing_order_info: 现有订单信息（用于下单任务）
            
        Returns:
            Dict: 处理结果
        """
        self.logger.info(f"🎯 开始任务分析 - 客户: {customer_id}")
        self.logger.info(f"📝 客户消息: {message}")
        
        try:
            # 确定可处理的任务
            available_tasks = self._get_available_tasks(message, conversation_history)
            
            if not available_tasks:
                self.logger.warning(f"⚠️ 没有找到合适的任务处理器 - 客户: {customer_id}")
                return self._create_fallback_response(customer_id, message)
            
            # 选择优先级最高的任务
            selected_task = self._select_task(available_tasks)
            
            # 执行任务
            result = self._execute_task(selected_task, message, conversation_history, customer_id, existing_order_info)
            
            # 更新统计信息
            self._update_stats(selected_task, result)
            
            self.logger.info(f"✅ 任务执行完成 - 任务类型: {result.get('task_type', '未知')}")
            return result
            
        except Exception as e:
            self.logger.error(f"❌ 任务处理失败: {str(e)}")
            return self._create_error_response(customer_id, message, str(e))
    
    def _get_available_tasks(self, message: str, conversation_history: list) -> List[str]:
        """获取可处理的任务列表"""
        available_tasks = []
        
        for task_name, task_processor in self.tasks.items():
            if task_processor.can_handle(message, conversation_history):
                available_tasks.append(task_name)
                self.logger.info(f"✅ 任务 '{task_name}' 可以处理此消息")
        
        return available_tasks
    
    def _select_task(self, available_tasks: List[str]) -> str:
        """选择优先级最高的任务"""
        if not available_tasks:
            return "customer_service"  # 默认呼叫客服
        
        # 按优先级排序
        sorted_tasks = sorted(available_tasks, key=lambda x: self.task_priority.get(x, 999))
        selected_task = sorted_tasks[0]
        
        self.logger.info(f"🎯 选择任务: {selected_task} (优先级: {self.task_priority.get(selected_task, 999)})")
        return selected_task
    
    def _execute_task(self, task_name: str, message: str, conversation_history: list, customer_id: str, existing_order_info: Dict = None) -> Dict[str, Any]:
        """执行指定任务"""
        task_processor = self.tasks[task_name]
        
        self.logger.info(f"🚀 执行任务: {task_name}")
        
        # 根据任务类型调用不同的处理方法
        if task_name == "order_processing":
            result = task_processor.process(message, conversation_history, customer_id, existing_order_info)
        else:
            result = task_processor.process(message, conversation_history, customer_id)
        
        # 添加任务管理器信息
        result["task_manager"] = {
            "selected_task": task_name,
            "available_tasks": self._get_available_tasks(message, conversation_history),
            "priority": self.task_priority.get(task_name, 999)
        }
        
        return result
    
    def _update_stats(self, task_name: str, result: Dict[str, Any]):
        """更新任务执行统计"""
        if task_name in self.execution_stats:
            self.execution_stats[task_name]["count"] += 1
            if result.get("success", False):
                self.execution_stats[task_name]["success"] += 1
            else:
                self.execution_stats[task_name]["failed"] += 1
    
    def _create_fallback_response(self, customer_id: str, message: str) -> Dict[str, Any]:
        """创建默认回复"""
        return {
            "task_type": "呼叫客服",
            "success": True,
            "response": "请稍等，正在呼叫人工客服。",
            "customer_id": customer_id,
            "message": message,
            "task_manager": {
                "selected_task": "customer_service",
                "available_tasks": [],
                "priority": 999
            }
        }
    
    def _create_error_response(self, customer_id: str, message: str, error: str) -> Dict[str, Any]:
        """创建错误回复"""
        return {
            "task_type": "呼叫客服",
            "success": False,
            "error": error,
            "response": "抱歉，系统出现异常，正在呼叫人工客服。",
            "customer_id": customer_id,
            "message": message,
            "task_manager": {
                "selected_task": "customer_service",
                "available_tasks": [],
                "priority": 999
            }
        }
    
    def get_execution_summary(self) -> Dict[str, Any]:
        """获取任务执行摘要"""
        total_count = sum(stats["count"] for stats in self.execution_stats.values())
        total_success = sum(stats["success"] for stats in self.execution_stats.values())
        total_failed = sum(stats["failed"] for stats in self.execution_stats.values())
        
        return {
            "total_executions": total_count,
            "total_success": total_success,
            "total_failed": total_failed,
            "success_rate": (total_success / total_count * 100) if total_count > 0 else 0,
            "task_breakdown": self.execution_stats,
            "task_priorities": self.task_priority
        }
    
    def get_task_summaries(self) -> List[str]:
        """获取所有任务的摘要"""
        summaries = []
        for task_name, task_processor in self.tasks.items():
            summary = task_processor.get_task_summary()
            summaries.append(f"📋 {task_name.upper()}: {summary}")
        return summaries
    
    def reset_stats(self):
        """重置统计信息"""
        for task_name in self.execution_stats:
            self.execution_stats[task_name] = {"count": 0, "success": 0, "failed": 0}
        self.logger.info("📊 任务执行统计已重置") 